package com.zxmzy.scaffold.core.widget.slideback

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.view.View
import android.view.animation.DecelerateInterpolator
import android.widget.FrameLayout
import kotlin.math.sign

/**
 * @author zhangxiaoming
 * @date 2023/8/31
 * @description 滑动返回视觉动画处理交接view
 */
@SuppressLint("ViewConstructor")
class SlideBackView constructor(context: Context, slideView: ISlideView) : View(context) {
    private lateinit var slideView: ISlideView
    private var animator: ValueAnimator? = null
    private var rate = 0f //曲线的控制点
    private val decelerateInterpolator = DecelerateInterpolator()

    init {
        setSlideView(slideView)
    }

    fun setSlideView(slideView: ISlideView): SlideBackView {
        this.slideView = slideView
        layoutParams = FrameLayout.LayoutParams(slideView.getWidth(), slideView.getHeight())
        return this
    }

    fun getSlideView(): ISlideView {
        return slideView
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.let { slideView.onDraw(it, rate) }
    }

    override fun onDetachedFromWindow() {
        cancelAnim()
        if (rate != 0f) {
            rate = 0f
            invalidate()
        }
        super.onDetachedFromWindow()
    }

    fun updateRate(updateRate: Float, hasAnim: Boolean) {
        var newRate: Float = if (updateRate > width) width.toFloat() else updateRate
        if (rate == newRate) return
        cancelAnim()
        if (!hasAnim) {
            rate = newRate
            invalidate()
            visibility = if (rate == 0f) GONE else VISIBLE
        }
        animator = ValueAnimator.ofFloat(rate, newRate).apply {
            duration = 200
            interpolator = decelerateInterpolator
            addUpdateListener {
                rate = it.animatedValue as Float
                postInvalidate()
                visibility = if (rate == 0f) GONE else VISIBLE
            }
        }
        animator?.start()
    }

    private fun cancelAnim() {
        animator?.let {
            if (it.isRunning) {
                it.cancel()
            }
        }
    }
}